package com.intelli.eve.core.impl.configuration;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Properties;

/**
 * Author: Sergey42
 * Date: 21.12.2014 20:44
 */
public class ConfigurationLoader {

    private ConfigurationLoader() {
    }

    public static void loadProperties(String classPath, Map<String, String> properties) {
        try (InputStream stream = get(classPath)) {
            loadProperties(stream, properties);
        } catch (Throwable e) {
            throw new Configuration.ConfigurationInitializationException(e);
        }
    }

    public static void loadProperties(Class clazz, String resourceName, Map<String, String> properties) {
        try (InputStream stream = get(clazz, resourceName)) {
            loadProperties(stream, properties);
        } catch (Throwable e) {
            throw new Configuration.ConfigurationInitializationException(e);
        }
    }

    private static void loadProperties(InputStream stream, Map<String, String> properties) throws Exception {
        InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
        Properties props = new Properties();
        props.load(reader);

        for (Object key : props.keySet()) {
            properties.put((String) key, (String) props.get(key));
        }
    }

    private static InputStream get(String classPath) {
        return ClassLoader.class.getResourceAsStream(classPath);
    }

    private static InputStream get(Class clazz, String resourceName) {
        return clazz.getResourceAsStream(resourceName);
    }
}
